package com.example.result.preference

import android.content.Context
import androidx.preference.PreferenceManager
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.File

class Config {
    companion object {
        private const val DEF_IP = "192.168.1.68"
        private const val DEF_PORT = "12345"
        fun getUrl(context: Context): HttpUrl {
            val ip = getIp(context)
            return "http://${ip}:${getPort(context)}/".toHttpUrl()

        }

        fun getUploadUrl(context: Context): HttpUrl {
            val ip = getIp(context)
            return "http://${ip}:${getUploadPort(context)}/".toHttpUrl()

        }

        fun getIp(context: Context): String? {
            return PreferenceManager.getDefaultSharedPreferences(context)
                .getString("ip", DEF_IP)
        }

        fun setIp(context: Context, ip: String) {
            PreferenceManager.getDefaultSharedPreferences(context).edit().putString("ip", ip)
                .apply()
        }

        fun getPort(context: Context): String? {
            return PreferenceManager.getDefaultSharedPreferences(context)
                .getString("port", DEF_PORT)
        }

        fun getUploadPort(context: Context): String? {
            return PreferenceManager.getDefaultSharedPreferences(context)
                .getString("uploadPort", DEF_PORT)
        }

        fun setPort(context: Context, port: String) {
            PreferenceManager.getDefaultSharedPreferences(context)
                .edit().putString("port", port).apply()
        }

        fun setUploadPort(context: Context, port: String) {
            PreferenceManager.getDefaultSharedPreferences(context)
                .edit().putString("uploadPort", port).apply()
        }

        fun getCrashDir(context: Context): File? {
            return context.getExternalFilesDir("crash")
        }
    }
}